package com.bsoft.gol.hcs.followup.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.bsoft.gol.hcs.enumcase.FollowTypeEnum;
import com.bsoft.gol.hcs.enumcase.FollowUpStatusEnum;
import com.bsoft.gol.hcs.enumcase.FusTabTypeEnum;
import com.bsoft.gol.hcs.enumcase.PlanProduceTypeEnum;
import com.bsoft.gol.hcs.followup.bean.FollowUpConst;
import com.bsoft.gol.hcs.followup.bean.request.*;
import com.bsoft.gol.hcs.followup.bean.response.*;
import com.bsoft.gol.hcs.followup.dao.FusAfterHosRecordDAO;
import com.bsoft.gol.hcs.followup.entity.HospitalDischargeFollowUpEntity;
import com.bsoft.gol.hcs.specialist.bean.request.VisitMedicalListRequest;
import com.bsoft.gol.hcs.specialist.bean.response.VisitMedicalListResponse;
import com.bsoft.gol.hcs.specialist.dao.*;
import com.bsoft.gol.hcs.specialist.entity.*;
import com.bsoft.gol.hcs.specialist.service.IFollowUpCommonService;
import com.bsoft.gol.hcs.utils.CommonUtils;
import com.bsoft.gol.hcs.utils.Constants;
import com.bsoft.gol.hcs.visitrecord.dao.VrInpatientVisitRecordDAO;
import com.bsoft.gol.hcs.visitrecord.dao.VrOutpatientVisitRecordDAO;
import com.bsoft.gol.hcs.visitrecord.entity.VrInpatientVisitRecord;
import ctd.account.UserRoleToken;
import ctd.controller.exception.ControllerException;
import ctd.mvc.upload.FileMetaEntity;
import ctd.mvc.upload.FileService;
import ctd.persistence.annotation.DAOTransaction;
import ctd.spring.boot.annotation.SsdevReference;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.BeanUtils;
import ctd.util.KeyGenerator;
import ctd.util.annotation.RpcService;
import ctd.util.http.HttpClientTemplate;
import ctd.util.http.support.HttpResult;
import hcn.api.service.brandnew.MedicalHistoryService;
import hcn.base.DoctorOrgs;
import hcn.base.Organization;
import hcn.base.VrOutpatientVisitRecord;
import hcn.bean.UserAllVo;
import hcn.bean.specialist.qo.GroupMemberRequest;
import hcn.protocol.brandnew.AdmissionNoteReq;
import hcn.protocol.brandnew.AdmissionNoteResp;
import hcn.protocol.brandnew.GetMedicalRecordInformationReq;
import hcn.protocol.brandnew.GetMedicalRecordInformationResp;
import hcn.service.base.IDepartmentService;
import hcn.service.base.IOrgDoctorsService;
import hcn.service.base.IOrganizationService;
import hcn.service.base.qo.ManageUnitTreeQo;
import hcn.service.base.vo.ManageUnitTreeVO;
import hcn.specialist.DocTeamFusAuthority;
import hcn.util.RpcUserToken;
import lombok.extern.slf4j.Slf4j;
import org.atag.core.exception.ServiceException;
import org.atag.dao.model.SimplePageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import pcn.service.web.BaseDeviceService;
import service.rpc.IDocTeamRpcService;
import service.rpc.IOrganizationRpcService;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 院后随访服务
 *
 * @author neoLin - 2022/05/20 13:37
 **/
@SsdevService("fusAfterHosRecordService")
@Slf4j
public class FusAfterHosRecordService {


    @SsdevReference("hcn.baseDeviceService")
    private BaseDeviceService baseDeviceService;

    @Resource
    private FusAfterHosRecordDAO fusAfterHosRecordDAO;

    @Resource
    private DocTeamFusAuthorityDAO docTeamFusAuthorityDAO;

    @Resource
    private FusAfterContactsDAO fusAfterContactsDAO;

    @SsdevReference("hcn.department")
    private IDepartmentService departmentService;

    @SsdevReference("hcn.orgDoctorsService")
    private IOrgDoctorsService orgDoctorsService;

    @SsdevReference("hcn.organization")
    private IOrganizationService organization;

    @Resource
    private VrOutpatientVisitRecordDAO vrOutpatientVisitRecordDAO;

    @Resource
    private VrInpatientVisitRecordDAO vrInpatientVisitRecordDAO;

    @Resource
    private FusAfterHealthEducationDAO fusAfterHealthEducationDAO;

    @Resource
    private FusAfterRequisitionRecordDAO fusAfterRequisitionRecordDAO;

    @Resource
    private FusAfterPendingRecordDAO fusAfterPendingRecordDAO;

    @Resource
    private FusAfterSatSurveyDAO fusAfterSatSurveyDAO;


    @SsdevReference("hcnInterface.medicalHistoryService")
    private MedicalHistoryService medicalHistoryService;

    @Resource
    private FollowPatientLabelDAO followPatientLabelDAO;

    @Autowired
    private IFollowUpCommonService followUpCommonService;

    @Resource
    private FollowUpRouteDAO followUpRouteDAO;

    @Resource
    private IDocTeamRpcService docTeamRpcService;

    @Resource
    private HospitalDischargeFollowUpService hospitalDischargeFollowUpService;

    @Autowired
    private FusAfterHosRecordContentDAO fusAfterHosRecordContentDAO;

    @Autowired
    private IOrganizationRpcService organizationRpcService;

    @Autowired
    PatientMedicalDataCollectDAO patientMedicalDataCollectDAO;

    @Autowired
    private FusAfterRecommendDeptDAO fusAfterRecommendDeptDAO;

    private UserAllVo getCurrentUserInfo() {
        UserAllVo userAllVo = baseDeviceService.getAllByOnline();
        if (Objects.isNull(userAllVo)) {
            throw new ServiceException("获取当前用户信息失败");
        }

        return userAllVo;
    }


    /**
     * 处理科室查询条件入参
     */
    @Deprecated
    private void dealWithDepartmentParam(FollowUpRecordListDTO dto) {
        String departmentId = dto.getDepartmentId();
        if (StringUtils.isEmpty(departmentId)) {
            return;
        }
        Integer followUpType = dto.getFollowUpType();
        List<Integer> deptType = new ArrayList<>();
        deptType.add(followUpType);
        String tenantId = UserRoleToken.getCurrentTenantId();
        ManageUnitTreeVO manageUnitTree = departmentService.getManageUnitTree(tenantId, deptType, 1);

        ManageUnitTreeVO.Department department = searchDepartment(manageUnitTree, departmentId);
        List<String> departmentIds = new ArrayList<>();
        if (Objects.isNull(department)) {
            departmentIds.add(departmentId);
        } else {
            departmentIds.add(department.getLocalDeptId());
            flatChildDepartment(department.getChildList(), departmentIds);
        }
        dto.setDepartmentIds(departmentIds);
    }

    /**
     * 取出所有子节点的科室代码
     */
    private void flatChildDepartment(List<ManageUnitTreeVO.Department> child, List<String> departmentIds) {
        if (CollectionUtils.isEmpty(child)) {
            return;
        }
        child.forEach(c -> {
            departmentIds.add(c.getLocalDeptId());
            flatChildDepartment(c.getChildList(), departmentIds);
        });
    }

    /**
     * 搜索科室
     */
    private ManageUnitTreeVO.Department searchDepartment(ManageUnitTreeVO tree, String departmentId) {
        List<ManageUnitTreeVO.Org> orgList = tree.getOrgList();
        if (CollectionUtils.isEmpty(orgList)) {
            return null;
        }
        for (ManageUnitTreeVO.Org org : orgList) {
            List<ManageUnitTreeVO.Department> deptList = org.getDeptList();
            ManageUnitTreeVO.Department department = searchDepartmentChild(deptList, departmentId);
            if (Objects.nonNull(department)) {
                return department;
            }

        }
        return null;
    }

    private ManageUnitTreeVO.Department searchDepartmentChild(List<ManageUnitTreeVO.Department> deptList, String departmentId) {
        if (CollectionUtils.isEmpty(deptList)) {
            return null;
        }
        for (ManageUnitTreeVO.Department dept : deptList) {
            if (departmentId.equals(dept.getLocalDeptId())) {
                return dept;
            }
            List<ManageUnitTreeVO.Department> child = dept.getChildList();
            ManageUnitTreeVO.Department department = searchDepartmentChild(child, departmentId);
            if (Objects.nonNull(department)) {
                return department;
            }
        }
        return null;
    }

    /**
     * 批量修改随访状态
     */
    @RpcService
    public void updateBatch(UpdateFollowStateDTO dto) {
        Integer operationType = dto.getOperationType();
        if (Objects.isNull(operationType)) {
            throw new ServiceException("操作类型不能为空");
        }

        List<String> recordIds = dto.getRecordIds();

        if (!CollectionUtils.isEmpty(recordIds)) {
            recordIds.forEach(id -> update(dto, id));
        }


    }

    private static final int OPERATION_LOCK = 0;
    private static final int OPERATION_UNLOCK = 1;
    private static final int OPERATION_CANCEL = 2;
    private static final int OPERATION_RECOVER = 3;

    /**
     * 更新随访状态
     */
    private void update(UpdateFollowStateDTO dto, String recordId) {
        Integer operationType = dto.getOperationType();
        // 操作类型 0锁定 1取消锁定 2取消随访 3恢复随访
        HospitalDischargeFollowUpEntity entity = HospitalDischargeFollowUpEntity.builder().recordId(recordId).build();
        FusAfterHosRecord future = new FusAfterHosRecord();
        future.setRecordId(recordId);
        switch (operationType) {
            case OPERATION_LOCK:
                future.setLockId(dto.getDocId());
                future.setLockName(dto.getDoctorName());
                future.setHangUpFlag(false);
                entity.setFuture(future);
                entity.lock();
                break;
            case OPERATION_UNLOCK:
                future.setLockId(dto.getDocId());
                future.setLockName(dto.getDoctorName());
                future.setHangUpFlag(false);
                entity.setFuture(future);
                entity.unlock();
                break;
            case OPERATION_CANCEL:
                future.setCancelId(dto.getDocId());
                future.setCancelName(dto.getDoctorName());
                future.setCancelTime(new Date());
                future.setCancelReason(dto.getCancelReason());
                future.setCancelType(dto.getCancelType());
                future.setFollowUpStatus(FollowUpStatusEnum.CANCEL.getStatus());
                future.setHangUpFlag(false);
                entity.setFuture(future);
                entity.cancel();
                break;
            case OPERATION_RECOVER:
                future.setFollowUpStatus(FollowUpStatusEnum.READY.getStatus());
                future.setHangUpFlag(false);
                entity.setFuture(future);
                entity.recover();
                break;
            default:
                break;
        }
    }


    /**
     * 执行随访计划 暂挂或者完成
     */
    @RpcService
    @DAOTransaction
    public void changeFollowUpStatus(ExecuteFollowUpDTO dto) {
        log.info("changeFollowUpStatus.dto:{}", JSON.toJSONString(dto));
        Integer processType = dto.getProcessType();
        if (Objects.isNull(processType)) {
            throw new ServiceException("操作类型不能为空");
        }
        UserAllVo userAllVo = baseDeviceService.getAllByOnline();
        dto.setExecuteId(userAllVo.getLocalDoctorId());
        dto.setExecuteName(userAllVo.getUserName());
        dto.setExecuteDeptId(userAllVo.getLocalDeptId());
        dto.setExecuteDeptName(userAllVo.getDeptName());
        String recordId = dto.getRecordId();

        HospitalDischargeFollowUpEntity entity = HospitalDischargeFollowUpEntity.builder().recordId(recordId).build();
        FusAfterHosRecord future = new FusAfterHosRecord();
        future.setRecordId(recordId);
        //随访状态类型（1暂挂 2完成）
        switch (processType) {
            case 1:
                future.setHangUpFlag(true);
                entity.setFuture(future);
                entity.hangUp(dto);
                //保存暂挂信息
                break;
            case 2:
                future.setFollowUpStatus(FollowUpStatusEnum.FINISH.getStatus());
                future.setHangUpFlag(false);

                entity.setFuture(future);
                entity.finish(dto);
                break;
        }

    }

    /**
     * 根据所选择的科室统计随访计划数量
     */
    @RpcService
    public FollowUpCountVO fusRecordGroupCount(FollowUpRecordListDTO dto) {
        //1.今日任务2.待执行3.已执行4.已取消5.我的工作
        dto.setTabType(1);
        Long todayCount = fusAfterHosRecordDAO.getCount(dto);
        dto.setTabType(2);
        Long todoCount = fusAfterHosRecordDAO.getCount(dto);
        dto.setTabType(3);
        Long finishCount = fusAfterHosRecordDAO.getCount(dto);
        dto.setTabType(4);
        Long cancelCount = fusAfterHosRecordDAO.getCount(dto);
        dto.setTabType(5);
        Long myWorkCount = fusAfterHosRecordDAO.getCount(dto);
        FollowUpCountVO vo = new FollowUpCountVO();
        vo.setTodayCount(todayCount);
        vo.setTodoCount(todoCount);
        vo.setFinishCount(finishCount);
        vo.setCancelCount(cancelCount);
        vo.setMyWorkCount(myWorkCount);

        return vo;
    }


    /**
     * 获取带数量的科室树
     */
    @RpcService
    public List<DepartmentTreeCountVO.Node> fusDeptTreeWithCount(FollowUpRecordListDTO dto) {
        //先查询出科室树
//        Integer followUpType = dto.getFollowUpType();
        String tenantId = UserRoleToken.getCurrentTenantId();
        //应产品要求 将此处的树改为平级展示
//        ManageUnitTreeVO manageUnitTree = departmentService.getManageUnitTree(tenantId, deptType, 1);
//        ManageUnitTreeVO manageUnitTree = departmentService.getManageUnitList(tenantId, deptType, 1);
        ManageUnitTreeQo qo = new ManageUnitTreeQo();
        qo.setTenantId(tenantId);
        qo.setOrganizationId(dto.getOrganizationId());
        qo.setJoinType(1);
        //应产品要求 将此处的树又改为树形展示
        List<ManageUnitTreeVO.Department> departments = departmentService.queryDeptListByOrgId(qo);
        //然后查询出所有的 已科室代码为维度的count值
        dto.setTenantId(tenantId);
        List<FollowUpUnitCountVO> deptCount = fusAfterHosRecordDAO.getFollowUpDeptCount(dto);
        List<FollowUpUnitCountVO> orgCount = fusAfterHosRecordDAO.getFollowUpOrgCount(dto);

        Map<String, Long> deptCountMap = new HashMap<>();
        Map<String, Long> orgCountMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(deptCount)) {
            deptCountMap = deptCount.stream().collect(Collectors.toMap(FollowUpUnitCountVO::getCode, FollowUpUnitCountVO::getTotalCount));
        }
        if (!CollectionUtils.isEmpty(orgCount)) {
            orgCountMap = orgCount.stream().collect(Collectors.toMap(FollowUpUnitCountVO::getCode, FollowUpUnitCountVO::getTotalCount));
        }
        Map<String, Long> finalDeptCountMap = deptCountMap;
//        Map<String, Long> finalOrgCountMap = orgCountMap;

        if(!CollectionUtils.isEmpty(departments)){
            return dealWithDepartmentNode(departments, finalDeptCountMap, dto.getOrganizationId());

        }
        return Collections.emptyList();
//        DepartmentTreeCountVO vo = new DepartmentTreeCountVO();
//
//
//
//        if (Objects.nonNull(manageUnitTree)) {
//            List<ManageUnitTreeVO.Org> orgList = manageUnitTree.getOrgList();
//            if (!CollectionUtils.isEmpty(orgList)) {
//                List<DepartmentTreeCountVO.Node> root = orgList.stream().map(org -> {
//                    String localOrgId = org.getLocalOrgId();
//
//                    DepartmentTreeCountVO.Node orgNode = new DepartmentTreeCountVO.Node();
//                    orgNode.setCount(finalOrgCountMap.getOrDefault(localOrgId, 0L));
//                    orgNode.setName(org.getOrgName());
//                    orgNode.setType(1);
//                    orgNode.setOrganizationId(localOrgId);
//                    List<ManageUnitTreeVO.Department> deptList = org.getDeptList();
//                    orgNode.setChild(dealWithDepartmentNode(deptList, finalDeptCountMap, localOrgId));
//                    return orgNode;
//                }).collect(Collectors.toList());
//                vo.setRoot(root);
//            }
//        }


//        return vo;
    }

    /**
     * 递归处理部门节点
     */
    private List<DepartmentTreeCountVO.Node> dealWithDepartmentNode(List<ManageUnitTreeVO.Department> deptList, Map<String, Long> finalDeptCountMap, String organizationId) {
        if (CollectionUtils.isEmpty(deptList)) {
            return Collections.emptyList();
        }

        return deptList.stream().map(d -> {
            DepartmentTreeCountVO.Node node = new DepartmentTreeCountVO.Node();
            String localDeptId = d.getLocalDeptId();
            node.setDepartmentId(localDeptId);
            node.setOrganizationId(organizationId);
            node.setName(d.getDeptName());
            node.setInpormtant(d.isInpormtant());
            node.setOutpatientUse(d.isOutpatientUse());
            node.setInpatientUse(d.isInpatientUse());
            node.setInpatientPlaceUse(d.isInpatientPlaceUse());
            node.setTechnologyUse(d.isTechnologyUse());
            node.setType(2);
            node.setChild(dealWithDepartmentNode(d.getChildList(), finalDeptCountMap, organizationId));
            node.setCount(finalDeptCountMap.getOrDefault(localDeptId, 0L));
            summaryTreeCount(node);
            return node;
        }).collect(Collectors.toList());
    }

    /**
     * 计算子节点合计
     */
    private Long summaryTreeCount(DepartmentTreeCountVO.Node node) {
        Long currentCount = node.getCount();
        if (Objects.isNull(currentCount)) {
            currentCount = 0L;
        }
        List<DepartmentTreeCountVO.Node> child = node.getChild();
        if (CollectionUtils.isEmpty(child)) {
            return currentCount;
        }
        for (DepartmentTreeCountVO.Node n : child) {
            if (Objects.nonNull(n) && Objects.nonNull(n.getCount())) {
                currentCount += n.getCount();
            }
        }
        node.setCount(currentCount);
        return currentCount;
    }

    /**
     * 查询当前用户有权限的随访路径
     */
    @RpcService
    public List<AuthFollowUpRouteVO> queryRoutesByDocId(AuthFollowUpRouteDTO dto) throws ControllerException {
        String docId = null;
        //医生站嵌入传入机构代码和医生代码查询医生id
        if (CommonUtils.isNotEmpty(dto.getOrganizationId()) && CommonUtils.isNotEmpty(dto.getDoctorId())) {
            Organization detailByLocalOrgId = organization.getOrgDetailByLocalOrgId(dto.getOrganizationId());
            if (null != detailByLocalOrgId) {
                List<DoctorOrgs> doctorOrgs = orgDoctorsService.queryDoctorOrgList(detailByLocalOrgId.getOrgId(), dto.getDoctorId());
                if (CommonUtils.isNotEmpty(doctorOrgs)) {
                    docId = doctorOrgs.get(0).getDoctorId();
                }
            }
        } else {
            //健康通通过token的线程变量获取
            UserAllVo userInfo = getCurrentUserInfo();
            docId = userInfo.getDoctorId();
        }

        if (CommonUtils.isEmpty(docId)) {
            return Collections.emptyList();
        }

        //已知用户医生编号 查询 医生有权限的团队
        GroupMemberRequest request = new GroupMemberRequest();
        request.setDocId(docId);
        request.setTeamType(dto.getTeamType());
        List<Long> teamIdList = docTeamRpcService.queryTeamIdList(request);

        if (CollectionUtils.isEmpty(teamIdList)) {
            return Collections.emptyList();
        }

        List<DocTeamFusAuthority> docTeamFusAuthorities = docTeamFusAuthorityDAO.queryByDocId(docId, teamIdList);

        if (CollectionUtils.isEmpty(docTeamFusAuthorities)) {
            return Collections.emptyList();
        }
        List<Long> routeIdList = docTeamFusAuthorities.stream()
                .map(DocTeamFusAuthority::getRouteId).distinct().collect(Collectors.toList());
        if (CollectionUtils.isEmpty(routeIdList)) {
            return Collections.emptyList();
        }
        //查询路径列表
        Integer followUpType = dto.getFollowUpType();
        List<FollowUpRoute> routeList = followUpRouteDAO.queryByIds(routeIdList);
        if (CollectionUtils.isEmpty(routeList)) {
            return Collections.emptyList();
        }
        if (Objects.nonNull(followUpType)) {
            routeList = routeList.stream().filter(r -> {
                Byte visitType = r.getVisitType();
                if(Objects.isNull(visitType)){
                    return false;
                }
                return visitType.equals(followUpType.byteValue());
            }).collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(routeList)) {
            return Collections.emptyList();
        }
        List<AuthFollowUpRouteVO> authRouteList = routeList.stream().map(r -> {
            AuthFollowUpRouteVO vo = new AuthFollowUpRouteVO();
            vo.setRouteId(r.getRouteId().toString());
            vo.setRouteName(r.getRouteName());
            vo.setDiseaseTypeId(r.getDiseaseTypeId());
            return vo;
        }).collect(Collectors.toList());
        if (dto.isShowManual() && routeIdList.contains(0L)) {
            AuthFollowUpRouteVO v = new AuthFollowUpRouteVO();
            v.setRouteId("0");
            v.setRouteName("手动设置的随访路径");
            authRouteList.add(v);
        }
        //筛选病种关联的路径
        Long diseaseTypeId = dto.getDiseaseTypeId();
        if(Objects.nonNull(diseaseTypeId)){
            authRouteList = authRouteList.stream().filter(r->diseaseTypeId.equals(r.getDiseaseTypeId())).collect(Collectors.toList());
        }
        return authRouteList;
    }

    /**
     * 查询随访计划列表
     */
    @RpcService
    public SimplePageInfo<FollowUpRecordListVO> recordList(FollowUpRecordListDTO dto) {
        dealWithDepartmentParam(dto);
        if (Objects.nonNull(dto.getRouteId()) && dto.getRouteId() == 0) {
            dto.setRouteId(null);
            dto.setShowManual(true);
        }
        SimplePageInfo<FollowUpRecordListVO> page = fusAfterHosRecordDAO.recordPage(dto);
        List<FollowUpRecordListVO> list = page.getList();
        if (!CollectionUtils.isEmpty(list)) {

            for (FollowUpRecordListVO vo : list) {

                //患者标签
                FollowPatientLabelEntity q = new FollowPatientLabelEntity();
                String patientType = vo.getPatientType();
                q.setSource(Integer.parseInt(patientType));
                q.setVisitNo(vo.getVisitNo());
                q.setOrganizationId(vo.getOrganizationId());

                List<FollowPatientLabelEntity> labels = followPatientLabelDAO.selectList(q);
                if (!CollectionUtils.isEmpty(labels)) {
                    List<String> collect =
                            labels.stream().map(FollowPatientLabelEntity::getDisputeType).collect(Collectors.toList());
                    vo.setPatientTag(collect);
                }

            }
        }
        return page;
    }

    /**
     * 查询门诊或住院记录列表
     *
     * @param request 入参
     * @return 记录信息列表
     */
    @RpcService
    public List<VisitMedicalListResponse> queryVisitMedicalList(VisitMedicalListRequest request) {

        //查询门诊或住院记录
        List<VisitMedicalListResponse> list =
                vrOutpatientVisitRecordDAO.queryVisitMedicalListByCard(request);
        if (CommonUtils.isEmpty(list)) {
            return list;
        }
        //查询处置
        for (VisitMedicalListResponse response : list) {
            //没机构名称时补充展示
            if (CommonUtils.isEmpty(response.getOrganizationName()) && CommonUtils.isNotEmpty(response.getOrganizationId())) {
                Organization organization = organizationRpcService.getOrgDetailByOrgCode(response.getOrganizationId());
                response.setOrganizationName(organization.getFullName());
            }

            List<Map<String, Object>> treatmentList =
                    patientMedicalDataCollectDAO.queryTreatmentListBybusinessId(response.getRecordId());
            if (CommonUtils.isEmpty(treatmentList)) {
                continue;
            }
            String itemNames = "";
            for (Map<String, Object> map : treatmentList) {
                itemNames = itemNames + map.get("itemName") + ";";
            }
            response.setItemNames(itemNames);
        }
        return list;
    }


    /**
     * 导出excel
     */
    @RpcService
    public String exportFollowUpExcel(FollowUpRecordListDTO dto) {
        dealWithDepartmentParam(dto);
        if (Objects.nonNull(dto.getRouteId()) && dto.getRouteId() == 0) {
            dto.setRouteId(null);
            dto.setShowManual(true);
        }
        List<FollowUpRecordListVO> followUpRecordListVOS = fusAfterHosRecordDAO.recordListForExcel(dto);
        if (CollectionUtils.isEmpty(followUpRecordListVOS)) {
            throw new ServiceException("没有要导出的数据");
        }
        Integer followUpType = dto.getFollowUpType();
        List<?> export;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        Set<String> excludeColumnFiledNames = new HashSet<>();
        Integer tabType = dto.getTabType();
        if (Objects.nonNull(tabType) && tabType != FusTabTypeEnum.CANCELED.getType()) {
            excludeColumnFiledNames.add("cancelReason");
            excludeColumnFiledNames.add("cancelTime");
            excludeColumnFiledNames.add("cancelName");
        }
        if (FollowUpConst.FOLLOW_UP_TYPE_OUT.equals(followUpType)) {
            //门诊
            export = followUpRecordListVOS.stream().map(p -> {
                FollowUpOutpatientRecordExportVO vo = new FollowUpOutpatientRecordExportVO();
                BeanUtils.copy(p, vo);
                Byte followUpStatus = p.getFollowUpStatus();
                vo.setFollowUpStatusText(getFollowUpStatusText(followUpStatus));
                vo.setPatientNumber(p.getOutpatientNumber());
                return vo;
            }).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(export)) {
                return null;
            }
            EasyExcel.write(bos, FollowUpOutpatientRecordExportVO.class).excludeColumnFiledNames(excludeColumnFiledNames).sheet("导出数据").doWrite(export);
        } else if (FollowUpConst.FOLLOW_UP_TYPE_IN.equals(followUpType)) {
            //住院
            export = followUpRecordListVOS.stream().map(p -> {
                FollowUpInpatientRecordExportVO vo = new FollowUpInpatientRecordExportVO();
                BeanUtils.copy(p, vo);
                Byte followUpStatus = p.getFollowUpStatus();
                vo.setFollowUpStatusText(getFollowUpStatusText(followUpStatus));
                vo.setPatientNumber(p.getInpatientNumber());
                return vo;
            }).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(export)) {
                return null;
            }
            EasyExcel.write(bos, FollowUpInpatientRecordExportVO.class).excludeColumnFiledNames(excludeColumnFiledNames).sheet("导出数据").doWrite(export);
        }

        String fileId = uploadExcel(bos, "随访导出数据.xlsx");
        return fileId;
    }

    private String getFollowUpStatusText(Byte status) {
        //随访状态0未随访 1 已随访 2待确认 3已取消 9 已终止
        if (Objects.isNull(status)) {
            return "";
        }
        String text;
        FollowUpStatusEnum statusEnum = FollowUpStatusEnum.getByStatus(status);
        if (Objects.isNull(statusEnum)) {
            return "";
        }
        switch (statusEnum) {
            case READY:
                text = "未随访";
                break;
            case FINISH:
                text = "已随访";
                break;
            case UN_CONFIRM:
                text = "待确认";
                break;
            case CANCEL:
                text = "已取消";
                break;
            case SUSPEND:
                text = "已终止";
                break;
            default:
                text = "";
                break;
        }
        return text;
    }

    /**
     * 手动添加随访计划,可批量
     */
    @RpcService
    @DAOTransaction
    public void saveBatch(SaveFollowUpPlanDTO dto) {

        List<String> recordIds = dto.getRecordIds();
        if (CollectionUtils.isEmpty(recordIds)) {
            return;
        }
        List<FusAfterHosRecord> insertList = recordIds.stream().map(recordId -> {
            FusAfterHosRecord record = fusAfterHosRecordDAO.get(recordId);
            if (Objects.isNull(record)) {
                return null;
            }
            return copyBaseValue(record, dto);

        }).filter(Objects::nonNull).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(insertList)) {
            return;
        }
        //批量插入
        insertList.forEach(i->{
            i.setRouteDetailType(dto.getRouteDetailType());
            fusAfterHosRecordDAO.insertSelective(i);
        });

        //插入表单 以及 满意度  健康宣教
        List<SaveFollowUpPlanDTO.Questionnaire> questionnaireList = dto.getQuestionnaireList();
        if (!CollectionUtils.isEmpty(questionnaireList)) {

            insertList.forEach(i -> {
                List<FusAfterRequisitionRecord> qInsetList = new ArrayList<>();
                questionnaireList.forEach(q -> {
                    FusAfterRequisitionRecord inset = new FusAfterRequisitionRecord();
                    inset.setFormId(KeyGenerator.randomGenerate());
                    inset.setRecordId(i.getRecordId());
                    inset.setCreateId(dto.getDocId());
                    inset.setExecuteId(dto.getDocId());
                    inset.setExecuteName(dto.getDoctorName());
                    inset.setCreateDt(new Date());
                    inset.setModifyDt(new Date());
                    inset.setQuestionnaireId(q.getQuestionnaireId());
                    inset.setQuestionnaireName(q.getQuestionnaireName());
                    qInsetList.add(inset);
                });
                qInsetList.forEach(q->fusAfterRequisitionRecordDAO.insertSelective(q));
            });

        }
        List<SaveFollowUpPlanDTO.Education> hosEduList = dto.getHosEduList();
        if (!CollectionUtils.isEmpty(hosEduList)) {

            insertList.forEach(i -> {
                List<FusAfterHealthEducation> hInsetList = new ArrayList<>();
                hosEduList.forEach(h -> {
                    FusAfterHealthEducation insert = new FusAfterHealthEducation();
                    insert.setId(KeyGenerator.randomGenerate());
                    insert.setRecordId(i.getRecordId());
                    insert.setEducationId(h.getEducationId());
                    insert.setEducationName(h.getEducationName());
                    insert.setDefaultPush(0);
                    insert.setCreateDt(new Date());
                    insert.setModifyDt(new Date());
                    hInsetList.add(insert);

                });
                hInsetList.forEach(h->fusAfterHealthEducationDAO.insertSelective(h));
            });

        }

        //保存复诊项目等随访内容
        List<FusAfterHosRecordContent> recordContentList = dto.getRecordContentList();
        if (!CollectionUtils.isEmpty(recordContentList)) {
            insertList.forEach(i -> {
                recordContentList.forEach(e -> {
                    e.setId(KeyGenerator.randomGenerate());
                    e.setGmtCreate(new Date());
                    e.setGmtModified(new Date());
                    e.setRecordId(i.getRecordId());
                    fusAfterHosRecordContentDAO.save(e);
                });
            });
        }

        //保存推荐科室
        FusAfterRecommendDept recommendDept = dto.getRecommendDept();
        if (CommonUtils.isNotEmpty(recommendDept)){
            insertList.forEach(i->{
                recommendDept.setId(KeyGenerator.randomGenerate());
                recommendDept.setRecordId(i.getRecordId());
                fusAfterRecommendDeptDAO.save(recommendDept);
            });
        }
    }

    private FusAfterHosRecord copyBaseValue(FusAfterHosRecord source, SaveFollowUpPlanDTO dto) {
        FusAfterHosRecord insert = new FusAfterHosRecord();
        insert.setRecordId(KeyGenerator.randomGenerate());
        insert.setTenantId(source.getTenantId());
        insert.setOrganizationId(source.getOrganizationId());
        insert.setOrganizationName(source.getOrganizationName());
        insert.setRouteDetailType(source.getRouteDetailType());
        insert.setDepartmentId(source.getDepartmentId());
        insert.setDepartmentName(source.getDepartmentName());
        insert.setDoctorId(source.getDoctorId());
        insert.setDocId(source.getDocId());
        insert.setDoctorName(source.getDoctorName());
        insert.setPatientId(source.getPatientId());
        insert.setCardType(source.getCardType());
        insert.setCardNumber(source.getCardNumber());
        insert.setPatientName(source.getPatientName());
        insert.setPatientSex(source.getPatientSex());
        insert.setPatientAge(source.getPatientAge());
        insert.setTelephone(source.getTelephone());
        insert.setAddress(source.getAddress());
        insert.setPlanTime(dto.getPlanTime());
        insert.setCreateId(dto.getDocId());
        insert.setCreateTime(new Date());
        insert.setRouteId(source.getRouteId());
        insert.setRouteName(source.getRouteName());
        insert.setRouteDetailId(source.getRouteDetailId());
        insert.setMedicalRecordId(source.getMedicalRecordId());
        insert.setMedicalRecordName(source.getMedicalRecordName());
        insert.setPatientMedicalCardNumber(source.getPatientMedicalCardNumber());
        insert.setPatientMedicalCardType(source.getPatientMedicalCardType());
        insert.setModifyDt(new Date());
        insert.setPatientType(source.getPatientType());
        insert.setOutpatientNumber(source.getOutpatientNumber());
        insert.setInpatientNumber(source.getInpatientNumber());
        insert.setVisitNo(source.getVisitNo());
        return insert;
    }

    /**
     * 添加随访联系人
     */
    @RpcService
    public void saveContacts(SaveContactsDTO dto) {
        String recordId = dto.getRecordId();
        if (StringUtils.isEmpty(recordId)) {
            return;
        }
        FusAfterHosRecord record = fusAfterHosRecordDAO.get(recordId);
        if (Objects.isNull(record)) {
            throw new ServiceException("随访记录不存在");
        }
        String tenantId = RpcUserToken.getTenantId();
        Date now = new Date();
        FusAfterContacts query = new FusAfterContacts();
        query.setPatientId(record.getPatientId());
        query.setTenantId(tenantId);
        query.setOrganizationId(record.getOrganizationId());
        FusAfterContacts contacts = fusAfterContactsDAO.selectOne(query);
        FusAfterContacts insertOrUpdate = new FusAfterContacts();
        insertOrUpdate.setContactsName(dto.getContactsName());
        insertOrUpdate.setContactsRemark(dto.getContactsRemark());
        insertOrUpdate.setContactsPhone(dto.getContactsPhone());
        insertOrUpdate.setContactsRelation(dto.getContactsRelation());
        insertOrUpdate.setPatientId(record.getPatientId());
        insertOrUpdate.setOrganizationId(record.getOrganizationId());
        insertOrUpdate.setTenantId(tenantId);
        insertOrUpdate.setModifyDt(now);
        if (Objects.isNull(contacts)) {
            insertOrUpdate.setId(KeyGenerator.randomGenerate());
            insertOrUpdate.setCreateDt(now);
            fusAfterContactsDAO.insertSelective(insertOrUpdate);
        } else {
            insertOrUpdate.setId(contacts.getId());
            fusAfterContactsDAO.updateSelective(insertOrUpdate);
        }


    }

    /**
     * 住院患者列表
     */
    @RpcService
    public SimplePageInfo<FusInpatientListVO> queryInpatientList(FusPatientListDTO dto) {
        return fusAfterHosRecordDAO.queryInpatientList(dto);
    }

    /**
     * 门诊患者列表
     */
    @RpcService
    public SimplePageInfo<FusOutpatientListVO> queryOutpatientList(FusPatientListDTO dto) {
        return fusAfterHosRecordDAO.queryOutpatientList(dto);
    }


    /**
     * 临时随访记录保存
     */
    @RpcService
    public List<String> savePatientAfterHos(SaveTempFollowUpPlanDTO dto) {
        Integer followUpType = dto.getFollowUpType();
        if (Objects.isNull(followUpType)) {
            throw new ServiceException("随访类型不能为空");
        }
        List<SaveTempFollowUpPlanDTO.Patient> patientNumbers = dto.getPatientNumbers();
        if (CollectionUtils.isEmpty(patientNumbers)) {
            return Collections.emptyList();
        }
        List<String> patientTag = dto.getPateintFlag();

        String tenantId = UserRoleToken.getCurrentTenantId();
        UserAllVo userInfo = getCurrentUserInfo();
        List<String> recordIdList = new ArrayList<>();
        if (FollowUpConst.FOLLOW_UP_TYPE_OUT.equals(followUpType)) {
            //查询所有的门诊记录
            List<VrOutpatientVisitRecord> outRecords = patientNumbers.stream().map(number -> vrOutpatientVisitRecordDAO.getVrOutpatientVisitRecord
                    (number.getPatientNumber(), number.getOrganizationId())).filter(Objects::nonNull).collect(Collectors.toList());

            if (CollectionUtils.isEmpty(outRecords)) {
                return Collections.emptyList();
            }
            recordIdList = outRecords.stream().map(out -> this.saveOutpatientTempPlan(out, dto, tenantId, userInfo)).collect(Collectors.toList());
            outRecords.forEach(out -> this.updateTags(followUpType, out.getVisitNo(), patientTag, out.getOrganizationId(), tenantId));

        } else if (FollowUpConst.FOLLOW_UP_TYPE_IN.equals(followUpType)) {
            //查询所有的住院记录
            List<VrInpatientVisitRecord> inRecords = patientNumbers.stream().map(number -> vrInpatientVisitRecordDAO.getVrInpatientVisitRecord
                    (number.getPatientNumber(), number.getOrganizationId())).filter(Objects::nonNull).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(inRecords)) {
                return Collections.emptyList();
            }
            recordIdList = inRecords.stream().map(in -> this.saveInpatientTempPlan(in, dto, tenantId, userInfo)).collect(Collectors.toList());
            inRecords.forEach(in -> this.updateTags(followUpType, in.getVisitNo(), patientTag, in.getOrganizationId(), tenantId));
        }
        return recordIdList;


    }

    /**
     * 获取暂挂列表
     *
     * @param recordId 随访记录id
     */
    @RpcService
    public List<HangUpFollowUpListVO> hangUpRecords(String recordId) {

        if (StringUtils.isEmpty(recordId)) {
            throw new ServiceException("随访记录id不能为空");
        }
        FusAfterPendingRecord query = new FusAfterPendingRecord();
        query.setRecordId(recordId);
        query.setFollowType(FollowTypeEnum.FUS_AFTER.getType());
        List<FusAfterPendingRecord> records = fusAfterPendingRecordDAO.selectList(query);
        if (CollectionUtils.isEmpty(records)) {
            return Collections.emptyList();
        }
        return records.stream().map(r -> {
            HangUpFollowUpListVO vo = new HangUpFollowUpListVO();
            BeanUtils.copy(r, vo);
            return vo;
        }).sorted((r1, r2) -> {
            Date createDt1 = r1.getCreateDt();
            Date createDt2 = r2.getCreateDt();
            return createDt1.compareTo(createDt2);
        }).collect(Collectors.toList());
    }

    /**
     * 获取随访记录对应的病历详情
     *
     * @param recordId 随访记录id
     */
    @RpcService
    public FollowUpDetailVO recordMedicalDetail(String recordId) {
        if (StringUtils.isEmpty(recordId)) {
            throw new ServiceException("随访记录id不能为空");
        }
        FusAfterHosRecord record = fusAfterHosRecordDAO.get(recordId);
        if (Objects.isNull(record)) {
            throw new ServiceException("随访记录不存在");
        }

        Integer patientType = record.getPatientType();
        String organizationId = record.getOrganizationId();
        String visitNo = record.getVisitNo();

        FollowUpDetailVO vo = new FollowUpDetailVO();

        if (FollowUpConst.FOLLOW_UP_TYPE_OUT.equals(patientType)) {
            //门诊
            VrOutpatientVisitRecord r = vrOutpatientVisitRecordDAO.getVrOutpatientVisitRecord(visitNo, organizationId);

            if (Objects.nonNull(r)) {
                GetMedicalRecordInformationReq data = new GetMedicalRecordInformationReq();
                data.setVisitId(r.getVisitNo());
                data.setVisitOrganization(r.getOrganizationId());
                try {
                    GetMedicalRecordInformationResp medicalRecordInformation =
                            medicalHistoryService.getMedicalRecordInformation(r.getOrganizationId(), data);
                    List<GetMedicalRecordInformationResp.MedicalRecord> medicalRecordLists =
                            medicalRecordInformation.getMedicalRecordLists();
                    if (!CollectionUtils.isEmpty(medicalRecordLists)) {
                        String webAddress = medicalRecordLists.get(0).getWebAddress();
                        vo.setWebUrl(webAddress);
                        vo.setWebMeta(getMetaData(webAddress));
                    }
                } catch (ControllerException e) {
                    log.error("获取门诊病历失败");
                }
            }
        } else if (FollowUpConst.FOLLOW_UP_TYPE_IN.equals(patientType)) {
            //住院
            VrInpatientVisitRecord r = vrInpatientVisitRecordDAO.getVrInpatientVisitRecord(visitNo, organizationId);
            if (Objects.nonNull(r)) {
                AdmissionNoteReq data = new AdmissionNoteReq();
                data.setVisitId(r.getVisitNo());
                data.setVisitOrganization(r.getOrganizationId());
                try {
                    AdmissionNoteResp resp = medicalHistoryService.getAdmissionNote(r.getOrganizationId(), data);
                    List<AdmissionNoteResp.AdmissionNote> requestLists = resp.getRequestLists();
                    if (!CollectionUtils.isEmpty(requestLists)) {
                        String medicalRecordWebAddress = requestLists.get(0).getMedicalRecordWebAddress();
                        vo.setWebUrl(medicalRecordWebAddress);
                        vo.setWebMeta(getMetaData(medicalRecordWebAddress));
                    }
                } catch (ControllerException e) {
                    log.error("获取门诊病历失败");
                }
            }
        }
        return vo;
    }

    /**
     * 获取随访详情
     *
     * @param recordId 随访记录id
     */
    @RpcService
    public FollowUpDetailVO recordDetail(String recordId) {
        if (StringUtils.isEmpty(recordId)) {
            throw new ServiceException("随访记录id不能为空");
        }
        FusAfterHosRecord record = fusAfterHosRecordDAO.get(recordId);
        if (Objects.isNull(record)) {
            throw new ServiceException("随访记录不存在");
        }

        Integer patientType = record.getPatientType();
        String organizationId = record.getOrganizationId();
        String visitNo = record.getVisitNo();
        String outpatientNumber = record.getOutpatientNumber();
        String inpatientNumber = record.getInpatientNumber();

        FollowUpDetailVO vo = new FollowUpDetailVO();

        if (FollowUpConst.FOLLOW_UP_TYPE_OUT.equals(patientType)) {
            //门诊
            VrOutpatientVisitRecord r = vrOutpatientVisitRecordDAO.getVrOutpatientVisitRecord(visitNo, organizationId);

            vo.setPatientNumber(outpatientNumber);
            vo.setOutpatientNumber(outpatientNumber);
            if (Objects.nonNull(r)) {
                vo.setCardType(r.getCardType());
                vo.setCardNumber(r.getCardNumber());
                vo.setOutpatientDept(r.getDepartmentName());
                vo.setVisitTime(r.getStartTime());
                vo.setOutDiagnosisName(r.getMainDiagnosisName());
                vo.setDoctorName(r.getDoctorName());
                vo.setDoctorId(r.getDoctorId());
                vo.setVisitNo(r.getVisitNo());
                vo.setOrganizationId(r.getOrganizationId());
                //病历信息获取已经单独拆分接口-recordMedicalDetail
//                GetMedicalRecordInformationReq data = new GetMedicalRecordInformationReq();
//                data.setVisitId(r.getVisitNo());
//                data.setVisitOrganization(r.getOrganizationId());
//                try {
//                    GetMedicalRecordInformationResp medicalRecordInformation = medicalHistoryService
//                    .getMedicalRecordInformation(r.getOrganizationId(), data);
//                    List<GetMedicalRecordInformationResp.MedicalRecord> medicalRecordLists =
//                    medicalRecordInformation.getMedicalRecordLists();
//                    if (!CollectionUtils.isEmpty(medicalRecordLists)) {
//                        String webAddress = medicalRecordLists.get(0).getWebAddress();
//                        vo.setWebUrl(webAddress);
//                        vo.setWebMeta(getMetaData(webAddress));
//                    }
//                } catch (ControllerException e) {
//                    log.error("获取门诊病历失败");
//                }
            }


        } else if (FollowUpConst.FOLLOW_UP_TYPE_IN.equals(patientType)) {
            //住院
            VrInpatientVisitRecord r = vrInpatientVisitRecordDAO.getVrInpatientVisitRecord(visitNo, organizationId);

            vo.setPatientNumber(inpatientNumber);
            vo.setInpatientNumber(inpatientNumber);
            if (Objects.nonNull(r)) {
                //todo 入院 出院科室
                vo.setCardType(r.getCardType());
                vo.setCardNumber(r.getCardNumber());
                vo.setAdmittingDept(r.getDepartmentName());
                vo.setDischargeDept(r.getDepartmentName());
                vo.setAdmittingDiagnosisName(r.getAdmissionDiagnosis());
                vo.setDisDiagnosisName(r.getDischargeDiagnosis());
                vo.setAdmittingTime(r.getAdmissionTime());
                vo.setDischargeTime(r.getDischargeTime());
                vo.setDoctorName(r.getDoctorName());
                vo.setDoctorId(r.getDoctorId());
                vo.setVisitNo(r.getVisitNo());
                vo.setOrganizationId(r.getOrganizationId());
                //病历信息获取已经单独拆分接口-recordMedicalDetail
//                AdmissionNoteReq data = new AdmissionNoteReq();
//                data.setVisitId(r.getVisitNo());
//                data.setVisitOrganization(r.getOrganizationId());
//                try {
//                    AdmissionNoteResp resp = medicalHistoryService.getAdmissionNote(r.getOrganizationId(), data);
//                    List<AdmissionNoteResp.AdmissionNote> requestLists = resp.getRequestLists();
//                    if (!CollectionUtils.isEmpty(requestLists)) {
//                        String medicalRecordWebAddress = requestLists.get(0).getMedicalRecordWebAddress();
//                        vo.setWebUrl(medicalRecordWebAddress);
//                        vo.setWebMeta(getMetaData(medicalRecordWebAddress));
//                    }
//                } catch (ControllerException e) {
//                    log.error("获取门诊病历失败");
//                }
            }


        }

        vo.setRouteDetailType(record.getRouteDetailType()==null?5:record.getRouteDetailType());
        vo.setFollowUpStatus(record.getFollowUpStatus());
        vo.setRecordId(record.getRecordId());
        vo.setPatientName(record.getPatientName());
        vo.setPatientAge(record.getPatientAge());
        vo.setPatientSex(record.getPatientSex());
        vo.setPlanTime(record.getPlanTime());
//        vo.setPatientNature("");

        vo.setMedicalNumber(record.getPatientMedicalCardNumber());
        vo.setPatientPhone(record.getTelephone());
        vo.setLockId(record.getLockId());
//        vo.setPatientBirthday(record.get);
        vo.setContactsName("");
        vo.setContactsRelation("");
        vo.setContactsPhone("");
        //获取随访联系人
        FusAfterContacts cQuery = new FusAfterContacts();
        cQuery.setPatientId(record.getPatientId());
        cQuery.setOrganizationId(record.getOrganizationId());
        cQuery.setTenantId(RpcUserToken.getTenantId());
        List<FusAfterContacts> fusAfterContacts = fusAfterContactsDAO.selectList(cQuery);
        if (!CollectionUtils.isEmpty(fusAfterContacts)) {
            FusAfterContacts contacts = fusAfterContacts.get(0);
            vo.setFollowUpContactsName(contacts.getContactsName());
            vo.setFollowUpContactsRelation(contacts.getContactsRelation());
            vo.setFollowUpContactsPhone(contacts.getContactsPhone());
            vo.setFollowUpContactsRemark(contacts.getContactsRemark());
        }
        vo.setPatientAddress(record.getAddress());

        //获取患者标签
        FollowPatientLabelEntity q = new FollowPatientLabelEntity();
        q.setOrganizationId(organizationId);
        q.setSource(patientType);
        q.setVisitNo(record.getVisitNo());

        List<FollowPatientLabelEntity> labels = followPatientLabelDAO.selectList(q);
        if (!CollectionUtils.isEmpty(labels)) {
            List<String> collect = labels.stream().map(FollowPatientLabelEntity::getDisputeType).collect(Collectors.toList());
            vo.setPatientTag(collect);
        }

        //获取随访表单列表
        FusAfterRequisitionRecord query = new FusAfterRequisitionRecord();
        query.setRecordId(recordId);
        List<FusAfterRequisitionRecord> fusAfterRequisitionRecords = fusAfterRequisitionRecordDAO.selectList(query);
        if (!CollectionUtils.isEmpty(fusAfterRequisitionRecords)) {
            List<FollowUpQuestionnaireDTO> questionnaireList = fusAfterRequisitionRecords.stream().map(r -> {
                FollowUpQuestionnaireDTO f = new FollowUpQuestionnaireDTO();
                f.setFormId(r.getFormId());
                f.setQuestionnaireId(r.getQuestionnaireId());
                f.setQuestionnaireName(r.getQuestionnaireName());
                f.setUserInfoId(r.getUserInfoId());
                return f;
            }).collect(Collectors.toList());
            vo.setQuestionnaireList(questionnaireList);
        }

        //获取健康宣教
        FusAfterHealthEducation q2 = new FusAfterHealthEducation();
        q2.setRecordId(recordId);
        List<FusAfterHealthEducation> educations = fusAfterHealthEducationDAO.selectList(q2);
        if (!CollectionUtils.isEmpty(educations)) {
            List<FollowUpEducationDTO> educationList = educations.stream().map(e -> {
                FollowUpEducationDTO education = new FollowUpEducationDTO();
                education.setId(e.getId());
                education.setEducationId(e.getEducationId());
                education.setEducationName(e.getEducationName());
                return education;
            }).collect(Collectors.toList());
            vo.setEducationList(educationList);
        }

        //获取满意度调查
        FusAfterSatSurvey q1 = new FusAfterSatSurvey();
        q1.setRecordId(recordId);
        List<FusAfterSatSurvey> satList = fusAfterSatSurveyDAO.selectList(q1);
        if (!CollectionUtils.isEmpty(satList)) {
            List<FollowUpSatQuestionnaireDTO> sates = satList.stream().map(e -> {
                FollowUpSatQuestionnaireDTO sat = new FollowUpSatQuestionnaireDTO();
                sat.setId(e.getId());
                sat.setQuestionnaireId(e.getQuestionnaireId());
                sat.setQuestionnaireName(e.getQuestionnaireName());
                sat.setPatientSurveyId(e.getPatientSurveyId());
                sat.setUserInfoId(e.getSurveyUserInfoId());
                return sat;
            }).collect(Collectors.toList());
            vo.setSatQuestionnaireList(sates);
        }

        return vo;

    }

    /**
     * 在随访详情页中的随访列表
     */
    @RpcService
    public List<SimpleFollowUpRecordListVO> recordListForSelect(SimpleFollowUpRecordListDTO dto) {
        dto.setTenantId(UserRoleToken.getCurrentTenantId());
        return fusAfterHosRecordDAO.queryRecordList(dto);
    }

    /**
     * 保存随访表单\满意度\健康宣教
     */
    @RpcService
    public void saveForm(SaveFollowUpFormDTO dto) {
        String recordId = dto.getRecordId();
        if (StringUtils.isEmpty(recordId)) {
            throw new ServiceException("随访记录id不能为空");
        }
        UserAllVo userInfo = getCurrentUserInfo();
        List<FollowUpQuestionnaireDTO> questionnaireList = dto.getQuestionnaireList();
        //保存随访表单
        if (!CollectionUtils.isEmpty(questionnaireList)) {
            questionnaireList.forEach(q -> saveOrUpdateQuestionnaire(q, userInfo, recordId));
        }

        //保存健康宣教
        List<FollowUpEducationDTO> educationList = dto.getEducationList();
        if (!CollectionUtils.isEmpty(educationList)) {
            educationList.forEach(e -> saveOrUpdateEducation(e,userInfo, recordId));
        }

        //满意度调查
        List<FollowUpSatQuestionnaireDTO> satQuestionnaireList = dto.getSatQuestionnaireList();
        if (!CollectionUtils.isEmpty(satQuestionnaireList)) {
            satQuestionnaireList.forEach(s -> saveOrUpdateSat(s, userInfo, recordId));
        }

    }

    /**
     * 删除健康宣教 删除随访表单 删除满意度调查
     */
    @RpcService
    public void deleteForm(DeleteFollowUpFormDTO dto) {
        String formId = dto.getFormId();
        String satFormId = dto.getSatFormId();
        String eduFormId = dto.getEduFormId();
        if (!StringUtils.isEmpty(formId)) {
            fusAfterRequisitionRecordDAO.remove(formId);
        }
        if (!StringUtils.isEmpty(satFormId)) {
            fusAfterSatSurveyDAO.remove(satFormId);
        }
        if (!StringUtils.isEmpty(eduFormId)) {
            fusAfterHealthEducationDAO.remove(eduFormId);
        }
    }

    @RpcService
    public void saveTags(SaveTagsDTO dto) {
        Integer followUpType = dto.getFollowUpType();
        if (Objects.isNull(followUpType)) {
            throw new ServiceException("随访类型不能为空");
        }

        String patientNumber = dto.getPatientNumber();
        if (StringUtils.isEmpty(patientNumber)) {
            throw new ServiceException("门诊号码或者住院号码不能为空");
        }

        List<String> patientTag = dto.getPatientTag();
        String organizationId = dto.getOrganizationId();

        updateTags(followUpType, patientNumber, patientTag, organizationId, UserRoleToken.getCurrentTenantId());

    }

    private void updateTags(Integer followUpType, String patientNumber, List<String> patientTag, String organizationId, String tenantId) {
        FollowPatientLabelEntity q = new FollowPatientLabelEntity();
        q.setSource(followUpType);
        q.setVisitNo(patientNumber);
        List<FollowPatientLabelEntity> labels = followPatientLabelDAO.selectList(q);
        if (!CollectionUtils.isEmpty(labels)) {
            labels.forEach(l -> followPatientLabelDAO.remove(l.getPatientLabelId()));
        }

        if (!CollectionUtils.isEmpty(patientTag)) {
            List<FollowPatientLabelEntity> insert = patientTag.stream().map(tag -> {
                FollowPatientLabelEntity entity = new FollowPatientLabelEntity();
                entity.setDisputeType(tag);
                entity.setOrganizationId(organizationId);
                entity.setTenantId(tenantId);
                entity.setVisitNo(patientNumber);
                entity.setSource(followUpType);
                return entity;
            }).collect(Collectors.toList());
            insert.forEach(i->followPatientLabelDAO.insertSelective(i));
        }
    }

    /**
     * 取消该患者的所有随访
     */
    @RpcService
    @DAOTransaction
    public void cancelAllPlan(CancelAllPlanDTO dto) {
        FusAfterHosRecord record = fusAfterHosRecordDAO.get(dto.getRecordId());
        if (Objects.isNull(record)) {
            throw new ServiceException("随访记录不存在");
        }
        String patientId = record.getPatientId();
        if (StringUtils.isEmpty(patientId)) {
            return;
        }
        //查询患者所有未执行的随访计划
        List<FusAfterHosRecord> all = fusAfterHosRecordDAO.findAllReadyPlanByPatientId(patientId);
        if (CollectionUtils.isEmpty(all)) {
            return;
        }
        UserAllVo userInfo = getCurrentUserInfo();

        all.forEach(a -> {
            HospitalDischargeFollowUpEntity entity = HospitalDischargeFollowUpEntity.builder().recordId(a.getRecordId()).build();
            FusAfterHosRecord future = new FusAfterHosRecord();
            future.setRecordId(a.getRecordId());
            future.setCancelId(userInfo.getLocalDoctorId());
            future.setCancelName(userInfo.getUserName());
            future.setCancelType(dto.getCancelType());
            future.setCancelReason(dto.getCancelReason());
            future.setCancelTime(new Date());
            future.setFollowUpStatus(FollowUpStatusEnum.CANCEL.getStatus());
            entity.setFuture(future);
            entity.cancel();
        });

    }

    /**
     * 保存随访表单
     */
    private void saveOrUpdateQuestionnaire(FollowUpQuestionnaireDTO dto, UserAllVo userInfo, String recordId) {
        String formId = dto.getFormId();

        FusAfterRequisitionRecord insertOrUpdate = new FusAfterRequisitionRecord();

        insertOrUpdate.setRecordId(recordId);
        insertOrUpdate.setCreateId(userInfo.getUserId());
        insertOrUpdate.setExecuteId(userInfo.getUserId());
        insertOrUpdate.setExecuteName(userInfo.getUserName());

        String questionnaireId = dto.getQuestionnaireId();
        if (StringUtils.isEmpty(questionnaireId)) {
            return;
        }
        insertOrUpdate.setQuestionnaireId(questionnaireId);
        insertOrUpdate.setQuestionnaireName(dto.getQuestionnaireName());
        insertOrUpdate.setUserInfoId(dto.getUserInfoId());
        Date now = new Date();
        if (StringUtils.isEmpty(formId)) {
            //新增
            insertOrUpdate.setFormId(KeyGenerator.randomGenerate());
            insertOrUpdate.setCreateDt(now);
            insertOrUpdate.setModifyDt(now);
            fusAfterRequisitionRecordDAO.insertSelective(insertOrUpdate);
        } else {
            //更新
            insertOrUpdate.setFormId(formId);
            insertOrUpdate.setModifyDt(now);
            fusAfterRequisitionRecordDAO.updateSelective(insertOrUpdate);
        }
    }

    /**
     * 保存健康宣教
     */
    private void saveOrUpdateEducation(FollowUpEducationDTO dto, UserAllVo userInfo, String recordId) {

        String id = dto.getId();

        FusAfterHealthEducation insertOrUpdate = new FusAfterHealthEducation();
        Long educationId = dto.getEducationId();
        if (Objects.isNull(educationId)) {
            return;
        }
        insertOrUpdate.setEducationId(educationId);
        insertOrUpdate.setRecordId(recordId);
        insertOrUpdate.setDefaultPush(0);
        insertOrUpdate.setEducationName(dto.getEducationName());

        Date now = new Date();
        insertOrUpdate.setModifyDt(now);
        if (StringUtils.isEmpty(id)) {
            insertOrUpdate.setId(KeyGenerator.randomGenerate());
            insertOrUpdate.setCreateDt(now);
            fusAfterHealthEducationDAO.insertSelective(insertOrUpdate);
        } else {
            insertOrUpdate.setId(id);
            insertOrUpdate.setEducationStatus("1");
            insertOrUpdate.setEducationTime(now);
            fusAfterHealthEducationDAO.updateSelective(insertOrUpdate);
            Long unread = fusAfterHealthEducationDAO.getCountContentByRecordId(recordId);
            //若状态都为已读，则修改随访计划状态为以执行
            if (unread <= Constants.ZORE) {
                fusAfterHosRecordDAO.updateFollowUpRecordsResult(recordId,Byte.valueOf(Constants.ONE_STRING),Byte.valueOf(Constants.ONE_STRING)
                        ,userInfo.getUserId(),userInfo.getUserName());
            }
        }
    }

    /**
     * 保存满意度调查
     */
    private void saveOrUpdateSat(FollowUpSatQuestionnaireDTO dto, UserAllVo userInfo, String recordId) {
        String id = dto.getId();

        FusAfterSatSurvey insertOrUpdate = new FusAfterSatSurvey();

        insertOrUpdate.setRecordId(recordId);
        insertOrUpdate.setCreateId(userInfo.getUserId());
        String questionnaireId = dto.getQuestionnaireId();
        if (StringUtils.isEmpty(questionnaireId)) {
            return;
        }
        insertOrUpdate.setQuestionnaireId(questionnaireId);
        insertOrUpdate.setQuestionnaireName(dto.getQuestionnaireName());
        insertOrUpdate.setPatientSurveyId(dto.getPatientSurveyId());
        insertOrUpdate.setSurveyUserInfoId(dto.getUserInfoId());
        Date now = new Date();
        if (StringUtils.isEmpty(id)) {
            //新增
            insertOrUpdate.setId(KeyGenerator.randomGenerate());
            insertOrUpdate.setCreateDt(now);
            insertOrUpdate.setModifyDt(now);
            fusAfterSatSurveyDAO.insertSelective(insertOrUpdate);
        } else {
            //更新
            insertOrUpdate.setId(id);
            insertOrUpdate.setModifyDt(now);
            fusAfterSatSurveyDAO.updateSelective(insertOrUpdate);
        }
    }


    /**
     * 生成临时的门诊随访计划
     */
    private String saveOutpatientTempPlan(VrOutpatientVisitRecord out, SaveTempFollowUpPlanDTO dto, String tenantId, UserAllVo userInfo) {
        //生成随访主表数据
        String recordId = KeyGenerator.randomGenerate();
        FusAfterHosRecord insert = new FusAfterHosRecord();
        insert.setRecordId(recordId);
        insert.setTenantId(tenantId);
        insert.setRouteDetailType(dto.getRouteDetailType());
        insert.setOrganizationId(out.getOrganizationId());
        insert.setOrganizationName(out.getOrganizationName());
        insert.setDepartmentId(out.getDepartmentId());
        insert.setDepartmentName(out.getDepartmentName());
        insert.setDoctorId(out.getDoctorId());
        insert.setDoctorName(out.getDoctorName());
        insert.setPatientId(out.getPatientId());
        insert.setCardType(out.getCardType());
        insert.setCardNumber(out.getCardNumber());
        insert.setPatientName(out.getPatientName());
        insert.setPatientSex(out.getPatientSex());
        if (Objects.nonNull(out.getPatientAge())) {
            insert.setPatientAge((int) out.getPatientAge());
        }
        insert.setTelephone(out.getTelephone());
        insert.setAddress(out.getAddress());
        insert.setPlanTime(dto.getPlanTime());
        insert.setCreateId(dto.getDocId());
        Date now = new Date();
        insert.setCreateTime(now);
        insert.setPatientMedicalCardNumber(out.getPatientMedicalCardNumber());
        insert.setPatientMedicalCardType(out.getPatientMedicalCardType());
        insert.setModifyDt(now);
        insert.setPatientType(1);
        insert.setOutpatientNumber(out.getPatientMedicalCardNumber());
        insert.setVisitNo(out.getVisitNo());
        if (CommonUtils.isNull(out.getEndTime())) {
            insert.setVisitTime(out.getStartTime());
        } else {
            insert.setVisitTime(out.getEndTime());
        }
        insert.setDocId(out.getDoctorId());
        insert.setDeptId(followUpCommonService.getDeptIdByLocalDeptId(out.getOrganizationId()
                , out.getDepartmentId()));
        //设置计划生成类型
        insert.setPlanProduceType(PlanProduceTypeEnum.HAND.getType());
        insert.setRouteName("手动设置的随访路径");
        boolean firstFollowUp = fusAfterHosRecordDAO.isFirstFollowUp(out.getPatientId(), out.getOrganizationId(), tenantId);
        if(firstFollowUp){
            insert.setFirstFlag(true);
        }
        fusAfterHosRecordDAO.insertSelective(insert);

        //院后随访计划生成，需要更新对应就诊类型记录的计划次数
        vrOutpatientVisitRecordDAO.updateFusAfterPlanTimes(out.getVisitNo(), out.getOrganizationId());

        //保存表单
        List<FollowUpQuestionnaireDTO> questionnaireList = dto.getQuestionnaireList();
        if (!CollectionUtils.isEmpty(questionnaireList)) {
            questionnaireList.forEach(q -> saveOrUpdateQuestionnaire(q, userInfo, recordId));
        }
        //保存健康宣教
        List<FollowUpEducationDTO> hosEduList = dto.getHosEduList();
        if (!CollectionUtils.isEmpty(hosEduList)) {
            hosEduList.forEach(e -> saveOrUpdateEducation(e,userInfo, recordId));
        }
        //保存复诊项目等随访内容
        List<FusAfterHosRecordContent> recordContentList = dto.getRecordContentList();
        if (!CollectionUtils.isEmpty(recordContentList)){
            recordContentList.forEach(e->{
                e.setId(KeyGenerator.randomGenerate());
                e.setGmtCreate(new Date());
                e.setGmtModified(new Date());
                e.setRecordId(recordId);
                fusAfterHosRecordContentDAO.save(e);
            });
        }

        //保存满意度调查
        List<FollowUpSatQuestionnaireDTO> satQuestionnaireList = dto.getSatQuestionnaireList();
        if (!CollectionUtils.isEmpty(satQuestionnaireList)) {
            satQuestionnaireList.forEach(s -> saveOrUpdateSat(s, userInfo, recordId));
        }

        //保存推荐科室
        FusAfterRecommendDept recommendDept = dto.getRecommendDept();
        if (CommonUtils.isNotEmpty(recommendDept)){
            recommendDept.setId(KeyGenerator.randomGenerate());
            recommendDept.setRecordId(recordId);
            fusAfterRecommendDeptDAO.save(recommendDept);
        }
        return recordId;

    }

    /**
     * 生成临时的住院随访计划
     */
    private String saveInpatientTempPlan(VrInpatientVisitRecord in, SaveTempFollowUpPlanDTO dto, String tenantId, UserAllVo userInfo) {
        Date now = new Date();
        String recordId = KeyGenerator.randomGenerate();

        FusAfterHosRecord insert = new FusAfterHosRecord();
        insert.setRecordId(recordId);
        insert.setRouteDetailType(dto.getRouteDetailType());
        insert.setTenantId(tenantId);
        insert.setOrganizationId(in.getOrganizationId());
        insert.setOrganizationName(in.getOrganizationName());
        insert.setDepartmentId(in.getDepartmentId());
        insert.setDepartmentName(in.getDepartmentName());
        insert.setDoctorId(in.getDoctorId());
        insert.setDoctorName(in.getDoctorName());
        insert.setPatientId(in.getPatientId());
        insert.setCardType(in.getCardType());
        insert.setCardNumber(in.getCardNumber());
        insert.setPatientName(in.getPatientName());
        insert.setPatientSex(in.getPatientSex());
        if (Objects.nonNull(in.getPatientAge())) {
            insert.setPatientAge((int) in.getPatientAge());
        }
        insert.setTelephone(in.getTelephone());
        insert.setAddress(in.getAddress());
        insert.setPlanTime(dto.getPlanTime());
        insert.setCreateId(dto.getDocId());
        insert.setCreateTime(now);
        insert.setPatientMedicalCardNumber(in.getPatientMedicalCardNumber());
        insert.setPatientMedicalCardType(in.getPatientMedicalCardType());
        insert.setModifyDt(now);
        insert.setPatientType(2);
        insert.setInpatientNumber(in.getInHospitalRecordCode());
        insert.setVisitNo(in.getVisitNo());
        insert.setDocId(in.getDoctorId());
        insert.setMedicalRecordNumber(in.getMedicalRecordNumber());
        insert.setVisitTime(in.getDischargeTime());
        insert.setDeptId(followUpCommonService.getDeptIdByLocalDeptId(in.getOrganizationId()
                , in.getDepartmentId()));
        //设置计划生成类型
        insert.setPlanProduceType(PlanProduceTypeEnum.HAND.getType());
        insert.setRouteName("手动设置的随访路径");
        boolean firstFollowUp = fusAfterHosRecordDAO.isFirstFollowUp(in.getPatientId(), in.getOrganizationId(), tenantId);
        if(firstFollowUp){
            insert.setFirstFlag(true);
        }
        fusAfterHosRecordDAO.insertSelective(insert);

        //院后随访计划生成，需要更新对应就诊类型记录的计划次数
        vrInpatientVisitRecordDAO.updateFusAfterPlanTimes(in.getVisitNo(), in.getOrganizationId());

        //保存表单
        List<FollowUpQuestionnaireDTO> questionnaireList = dto.getQuestionnaireList();
        if (!CollectionUtils.isEmpty(questionnaireList)) {
            questionnaireList.forEach(q -> saveOrUpdateQuestionnaire(q, userInfo, recordId));
        }
        //保存健康宣教
        List<FollowUpEducationDTO> hosEduList = dto.getHosEduList();
        if (!CollectionUtils.isEmpty(hosEduList)) {
            hosEduList.forEach(e -> saveOrUpdateEducation(e,userInfo, recordId));
        }
        //保存复诊项目等随访内容
        List<FusAfterHosRecordContent> recordContentList = dto.getRecordContentList();
        if (!CollectionUtils.isEmpty(recordContentList)){
            recordContentList.forEach(e->{
                e.setId(KeyGenerator.randomGenerate());
                e.setGmtCreate(new Date());
                e.setGmtModified(new Date());
                e.setRecordId(recordId);
                fusAfterHosRecordContentDAO.save(e);
            });
        }

        //保存满意度调查
        List<FollowUpSatQuestionnaireDTO> satQuestionnaireList = dto.getSatQuestionnaireList();
        if (!CollectionUtils.isEmpty(satQuestionnaireList)) {
            satQuestionnaireList.forEach(s -> saveOrUpdateSat(s, userInfo, recordId));
        }

        //保存推荐科室
        FusAfterRecommendDept recommendDept = dto.getRecommendDept();
        if (CommonUtils.isNotEmpty(recommendDept)){
            recommendDept.setId(KeyGenerator.randomGenerate());
            recommendDept.setRecordId(recordId);
            fusAfterRecommendDeptDAO.save(recommendDept);
        }

        return recordId;
    }


    /**
     * 获取电子病历原始数据
     */
    private String getMetaData(String url) {
        HttpResult httpResult;
        try {
            httpResult = HttpClientTemplate.instance().get(url, null);

            return httpResult.getBody();
        } catch (Exception e) {
            log.error("获取电子病历失败");
        }
        return "";
    }

    /**
     * 随访人员统计
     */
    @RpcService
    public SimplePageInfo<FollowUpSatDocVO> doctorFusStatistics(FollowUpSatDocDTO dto){
        return hospitalDischargeFollowUpService.doctorFusStatistics(dto);
    }

    /**
     * 科室随访统计
     */
    @RpcService
    public SimplePageInfo<FollowUpSatVO> deptFusStatistics(FollowUpSatDTO dto) {
        return hospitalDischargeFollowUpService.deptFusStatistics(dto);
    }

    /**
     * 科室随访统计
     */
    @RpcService
    public SimplePageInfo<FollowUpSatVO> routeFusStatistics(FollowUpSatDTO dto) {
        return hospitalDischargeFollowUpService.routeFusStatistics(dto);
    }

    @RpcService
    public String doctorFusExport(FollowUpSatDocDTO dto) {
        List<FollowUpSatDocVO> dataList = hospitalDischargeFollowUpService.doctorFusStatisticsExport(dto);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        EasyExcel.write(bos, FollowUpSatDocVO.class).sheet("导出数据").doWrite(dataList);
        return uploadExcel(bos, "随访人员工作量统计.xlsx");
    }


    @RpcService
    public String routeFusExport(FollowUpSatDTO dto) {
        List<FollowUpSatVO> dataList = hospitalDischargeFollowUpService.routeFusStatisticsExport(dto);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        Set<String> excludeColumnFiledNames = new HashSet<>();
        excludeColumnFiledNames.add("departmentName");
        EasyExcel.write(bos, FollowUpSatVO.class).excludeColumnFiledNames(excludeColumnFiledNames).sheet("导出数据").doWrite(dataList);
        String fileName = "路径随访工作量统计.xlsx";
        return uploadExcel(bos, fileName);
    }


    @RpcService
    public String deptFusExport(FollowUpSatDTO dto) {
        List<FollowUpSatVO> dataList = hospitalDischargeFollowUpService.deptFusStatisticsExport(dto);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        Set<String> excludeColumnFiledNames = new HashSet<>();
        excludeColumnFiledNames.add("routeName");
        EasyExcel.write(bos, FollowUpSatVO.class).excludeColumnFiledNames(excludeColumnFiledNames).sheet("导出数据").doWrite(dataList);
        String fileName = "科室随访工作量统计.xlsx";
        return uploadExcel(bos, fileName);
    }

    private String uploadExcel(ByteArrayOutputStream bos, String fileName){
        byte[] bytes = bos.toByteArray();
        int filesize = bytes.length;
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);

        UserRoleToken token = UserRoleToken.getCurrent();
        FileMetaEntity fileMeta = new FileMetaEntity();
//        fileMeta.setManageUnit(token.getManageUnit());
        fileMeta.setLastModify(new Date());
        fileMeta.setUploadTime(new Date());
        fileMeta.setMode(31);
        fileMeta.setFileName(fileName);
        fileMeta.setContentType("application/octet-stream");
        fileMeta.setOwner(token.getUserId());
        fileMeta.setFileSize(filesize);
        fileMeta.setCatalog("export-file");
        String fileId = null;
        try {
            fileId = FileService.instance().upload(fileMeta, bis);
        } catch (Exception e) {
            log.error("文件上传失败", e);
        }
        return fileId;
    }


    /**
     * 更改慢病管理复诊预约-随访记录状态为 已预约
     *
     * @param recordId
     */
    @RpcService
    public void updateFollowUpStatusById(String recordId) {
        try {
            fusAfterHosRecordDAO.updateFollowUpStastusById(Byte.valueOf(Constants.TWO_STRING), recordId);
        } catch (Throwable throwable) {
            log.info("修改院后随访状态失败");
        }
    }
}
